package gr.aueb.cs.mscis.chordroid;

import java.util.List;

import gr.aueb.cs.mscis.R;
import gr.aueb.cs.mscis.chordroid.chord.Node;
import gr.aueb.cs.mscis.chordroid.chord.NodeIdentifier;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class NodeInfoActivity extends Activity  {
	
	private Handler mHandler;
	private int i=0;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.nodeinfolayout);
		mHandler = new Handler();
        mHandler.post(mUpdate);
        
        Button fileAppButton = (Button)findViewById(R.id.button1);
        fileAppButton.setOnClickListener(new View.OnClickListener() {
          public void onClick(View view) {
            Intent intent = new Intent(NodeInfoActivity.this, FileAppActivity.class);
            startActivity(intent);
          }
        });
        
        Button dhtManagerButton = (Button) findViewById(R.id.button2);
        dhtManagerButton.setOnClickListener(new View.OnClickListener() {
          public void onClick(View view) {
              Intent intent = new Intent(NodeInfoActivity.this, DHTManagerActivity.class);
              startActivity(intent);
          }
        });
      }
        
        
        
        
        
	Node myLuckyNode;
		
    private Runnable mUpdate = new Runnable(){
    	//emfanizoume sto UI ta hashes twn successor tou kai tou predeccessor tou
		public void run() {
				Node myLuckyNode=ChordroidService.getMyLuckyNode();
				if (myLuckyNode.getKey()!=null)setMyInfo( myLuckyNode.getKey()+" "+i);
				if (myLuckyNode.getPredecessor()!=null) setMyPredeccessprInfo(myLuckyNode.getPredecessor().getHash());
				if (myLuckyNode.getSuccessor()!=null) setMySuccessorInfo(myLuckyNode.getSuccessor().getHash());
				if (!myLuckyNode.getSuccessorList().isEmpty()) setSuccessorList(myLuckyNode.getSuccessorList());
				mHandler.postDelayed(this, 1000);	
				i++;
			}

			
		};
		
	private void setSuccessorList(List<NodeIdentifier> successorList) {
		try{
			String hash=successorList.get(1).getHash();
			 ((TextView)findViewById(R.id.textView5)).setText(String.valueOf("My 2nd successor is: "+ hash));
		}catch (IndexOutOfBoundsException e){}
			
			
		}		

	
	public  void setMyInfo(String hash){
		((TextView)findViewById(R.id.textView2)).setText(String.valueOf("I am: "+ hash));
	}
	
	public  void setMySuccessorInfo(String hash){
		((TextView)findViewById(R.id.textView3)).setText(String.valueOf("My successor is: "+ hash));
	}

	public  void setMyPredeccessprInfo(String hash){
		((TextView)findViewById(R.id.textView4)).setText(String.valueOf("My predeccessor is: "+ hash));
	}
	
}
